#include "LayoutManager.h"
#include "MainComponent.h"

LayoutManager::LayoutManager(MainComponent * mainComponent_) : mainComponent (mainComponent_)
{}

LayoutManager::~LayoutManager()
{}

void LayoutManager::showContainer(ContainerComponent * container)
{
	mainComponent->addAndMakeVisible(container);
	container->setContainerShown(true);
}

void LayoutManager::hideContainer(ContainerComponent * container)
{
	mainComponent->removeChildComponent(container);
	container->setContainerShown(false);
}


void LayoutManager::doLayout()
{
	int newWidth = 0;
	int newHeight = 0;
	int newX = 0;
	int newY = 0;

	if(mainComponent->isValidComponent())
	{
		ContainerComponent * rootContainer = mainComponent->getRootContainer();
		
		placeChildContainers(rootContainer, newWidth, newHeight);

		//placeTitleLabel();

		rootContainer->setTopLeftPosition(mainComponent->getWidth() / 2 - rootContainer->getWidth() / 2, rootContainer->getY());
		mainComponent->setSize(newWidth, newHeight);
		mainComponent->setTopLeftPosition(Desktop::getInstance().getMainMonitorArea().getWidth()/2 - mainComponent->getWidth()/2, mainComponent->getY());


	}

	/*
	if(elementToShowText)
	{
		int titleX = elementToShowText->getX() + elementToShowText->getWidth() / 2 - title->getWidth() / 2;
		title->setTopLeftPosition(titleX, maxH + 5);

		maxH = title->getBottom();
		
		if(title->getRight() > maxW)
			maxW += title->getRight() - maxW; 
		if(title->getX() < 0)
		{
			maxW -= title->getX();
			title->setTopLeftPosition(0, title->getY());
		}
	}

	*/
}

void LayoutManager::placeChildContainers(ContainerComponent * parent, int& w, int &h)
{
	ElementComponent * el = parent->getParentElement();
	int cx = 0;
	if(el)
		cx = el->getX();

	parent->setTopLeftPosition(cx, h);

	w = jmax(w, parent->getWidth());
	h = jmax(h, parent->getY() + parent->getHeight());


	for(int i = 0; i < parent->getNumChildComponents(); i++)
	{
		ElementComponent * element = parent->getElementAt(i);

		if(element->getDockElement()->getType() == container)
		{
			ContainerComponent * container = element->getChildContainer();
			
			if(container && container->isContainerShown())
			{
				placeChildContainers(container, w, h);
			}
		}
		else
		{
			
		}
	}
}